package zcxn.microService.dofile;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import zcxn.microService.bean.BattParamsInfo;
import zcxn.microService.bean.GlobalAllConfigInfo;
import zcxn.microService.bean.GlobalPartConfigInfo;
import zcxn.microService.service.YamlPropertiesUtil;

public class CopyFileAndUpdateYaml {
	

	public static void main(String[] args) throws IOException {
		// 将文件二进制文件拷贝到对应的文件夹中
//		String gridId = "1006";
//		CopyFileAndUpdateYaml y = new CopyFileAndUpdateYaml();
//		GlobalConfigInfo global=new GlobalConfigInfo();
//		y.copyFileAndUpdateYaml(gridId, "sahhdshdsahjdhsajdhssjsj1006",global);
	}

	/**
	 * 微电网ID 和serviceName 生成对应的文件 二进制文件 、start.sh 、yaml文件
	 * 
	 * @param gridId
	 * @param buildfileName
	 * @param global
	 * @param batt
	 * @throws IOException
	 */
	public void copyFileAndUpdateYaml(String gridId, String buildfileName, GlobalPartConfigInfo global,
			BattParamsInfo batt) throws IOException {
//		this.updateYamlInfo(gridId, global, batt);
		this.copyBuildFile(gridId, buildfileName);
		this.addStartFile(global.getServiceName(), gridId);
		packageMicroService(global.getServiceName(), gridId);
	}

	/**
	 * 打包生成serviceName.sh.tgz 文件
	 * 
	 * @param servcieName
	 * @param gridId
	 * @return
	 */
	public static File packageMicroService(String servcieName, String gridId) {
		String yamlpath = "F:" + File.separator + "DataLogger_build" + File.separator + "GridId".concat(gridId )
				+ File.separator + "config".concat(gridId + "").concat(".yaml");
		String buildPath = "F:" + File.separator + "DataLogger_build" + File.separator + "GridId".concat(gridId)
				+ File.separator + servcieName;
		String startPath = "F:" + File.separator + "DataLogger_build" + File.separator + "GridId".concat(gridId)
				+ File.separator + servcieName.concat(".sh");
		File[] sources = new File[3];
		sources[0] = new File(yamlpath);
		sources[1] = new File(buildPath);
		sources[2] = new File(startPath);
		File target = new File(startPath.concat(".tgz"));
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(target);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		TarArchiveOutputStream os = new TarArchiveOutputStream(out);
		for (File file : sources) {
			try {
				os.putArchiveEntry(new TarArchiveEntry(file));
				IOUtils.copy(new FileInputStream(file), os);
				os.closeArchiveEntry();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (os != null) {
			try {
				os.flush();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return target;
	}

	/**
	 * 二进制文件的copy
	 * 
	 * @param gridId
	 * @param buildfileName
	 * @throws IOException
	 */
	public void copyBuildFile(String gridId, String buildfileName) throws IOException {
		copyAndRenameFile("4dcdaf89a507670f74c62f38538733a7_dev_ttyUSB1", gridId, buildfileName);
	}

	
	

	/**
	 * 将目标文件拷贝到目标目录下，重新命令的方法
	 * 
	 * @param inFileName
	 * @param outpath
	 * @param outFileName
	 * @throws IOException
	 */
	public static void copyAndRenameFile(String inFileName, String gridId, String outFileName) throws IOException {
		long start = System.currentTimeMillis();
		System.err.println("=======Start========");
		// 本地保存文件的位置
		String rootPath = "F:" + File.separator + "DataLogger_build" + File.separator;
		// 输入文件路径
		String inPath = rootPath + inFileName;
		File inFile = new File(inPath);
		// 判断文件是否存在
		if (!inFile.exists()) {
			System.out.println("源文件不存在！！");
			System.exit(2);
		} else {
			System.out.println(String.format("源文件存在 ： %s", inFile.getPath()));
		}
		// 输出文件路径
		String outPath = rootPath + File.separator + "GridId".concat(gridId) + File.separator + outFileName;
		File outFile = new File(outPath);
		// 判断输出文件路径是否存在，不存在 就创建
		if (!outFile.exists()) {
			outFile.getParentFile().mkdirs();
		} else {
			outFile.delete();
			System.out.println("目标文件存在已经被删除");
		}
		InputStream is = new FileInputStream(inFile);
		OutputStream os = new FileOutputStream(outFile);
		int tmp = 0;
		byte[] content = new byte[1024];
		while (((tmp = is.read(content)) != -1)) {
			os.write(content, 0, tmp);
		}
		System.out.println(String.format("目标文件存在 ： %s", outFile.getPath()));
		System.err.println(String.format("From : %s >>>  To: %s", inFile.getPath(), outFile.getPath()));
		is.close();
		os.close();
		long end = System.currentTimeMillis();
		System.out.println(String.format("一共花费为了 %s 毫秒", end - start));
		System.err.println("=======End========");
	}

	public void addStartFile(String serviceName, String gridId) throws IOException {
		String outFileName = serviceName.concat(".sh");
		String rootPath = "F:" + File.separator + "DataLogger_build" + File.separator;
		String outPath = rootPath + File.separator + "GridId".concat(gridId) + File.separator + outFileName;

		String start = "./4dcdaf89a507670f74c62f38538733a7_dev_ttyUSB1 -c configwangzong.yaml";
		String context = "start = \"./".concat(serviceName).concat(" -c ").concat("config").concat(gridId)
				.concat(".yaml\"");

		OutputStream os = new FileOutputStream(new File(outPath));
		byte[] bytes = context.getBytes();
		os.write(bytes, 0, bytes.length);
		os.close();
		os.flush();
		System.out.println(context);
	}

	/**
	 * 替换yaml 中的内容（弃用）
	 * 
	 * @param srcList
	 * @param path
	 * @param globalMap
	 * @throws IOException
	 */
	public void replacTextContent(List<String> srcList, String path, Map globalMap) throws IOException {
		// 原有的内容
		String srcStr = "coll_freq: 5";
		// 要替换的内容
		String replaceStr = "coll_freq: " + Integer.parseInt(((String) globalMap.get("coll_freq")).trim());

		String srcStr1 = "soc_update_cycle: 5";
		String replaceStr1 = "soc_update_cycle: "
				+ Integer.parseInt(((String) globalMap.get("soc_update_cycle")).trim());
		// 读
		File file = new File(path);
		FileReader in = new FileReader(file);
		BufferedReader bufIn = new BufferedReader(in);
		// 内存流, 作为临时流
		CharArrayWriter tempStream = new CharArrayWriter();
		// 替换
		String line = null;
		while ((line = bufIn.readLine()) != null) {
			// 替换每行中, 符合条件的字符串
			line = line.replaceAll(srcStr, replaceStr);
			// 将该行写入内存
			tempStream.write(line);
			// 添加换行符
			tempStream.append(System.getProperty("line.separator"));
		}
		// 关闭 输入流
		bufIn.close();
		// 将内存中的流 写入 文件
		FileWriter out = new FileWriter(file);
		tempStream.writeTo(out);
		out.close();
		System.out.println("path:" + path);

	}
}
